<?php
namespace app\index\logic;

use app\index\model\UserModel;
use think\Cookie;
use think\Session;

class LoginLogic extends BaseLogic
{
    public function check_login(){
        $user_info = Session::get('user');
        if($user_info){//session有信息，代表已经登录，刷新cookie时间
            $this->refresh($user_info['id'],$user_info['mobile'],$user_info['password']);
            return true;
        }
        $user_info = Cookie::get('user');
        if($user_info){//cookie有信息，代表登录过，检查cookie中的password;
            $password = $user_info['password'];
            $model = new UserModel();
            $info = $model->where(['mobile'=>$user_info['mobile']])->find();
            if($info['password'] == $password){
                $this->refresh($info['id'],$info['mobile'],$info['password']);
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    public function login($mobile){
        $userModel = new UserModel();
        $user = $userModel->where(['mobile'=>$mobile])->find();
        if(!$user){//账号没注册
            if($userModel->add_user($mobile) === false){//注册1个账号
                $this->err = '注册登录失败';
                return false;
            }else{
                $user = UserModel::get(['mobile'=>$mobile]);
                $this->refresh($user['id'],$user['mobile'],$user['password']);
                return true;
            }
        }else{
            $this->refresh($user['id'],$user['mobile'],$user['password']);
            return true;
        }
    }

    private function refresh($user_id,$mobile,$password){
        $data = [];
        $data['mobile'] = $mobile;
        $data['password'] = $password;
        Cookie::set('user',$data,60*60*24*7);
        $data['id'] = $user_id;
        Session::set('user',$data);
    }
}
